package com.school.information.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.information.dto.RoleDTO;
import com.school.information.entity.SysRoleEntity;
import com.school.information.entity.SysUserEntity;
import com.school.information.enums.result.SysResultEnum;
import com.school.information.enums.status.EnabledEnum;
import com.school.information.qo.SysRoleQO;
import com.school.information.service.SysRoleMenuService;
import com.school.information.service.SysRoleService;
import com.school.information.service.SysUserService;
import com.school.information.utils.NumberUtil;
import com.school.information.utils.ResultUtil;
import com.school.information.vo.RoleVO;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * (SysRole)表控制层
 *
 * @author ycc
 * @since 2023-05-28 23:28:12
 */
@RestController
@RequestMapping("sysRole")
@Slf4j
public class SysRoleController {
    /**
     * 服务对象
     */
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserService userService;
    @Resource
    private SysRoleMenuService roleMenuService;

    /**
     * 分页查询所有数据
     *
     * @return 所有数据
     */
    @PostMapping("/pageList")
    public ResultUtil pageList(@RequestBody SysRoleQO sysRole) {
        IPage<SysRoleEntity> page = sysRoleService.pageList(sysRole);
        if (CollectionUtil.isEmpty(page.getRecords())) {
            return ResultUtil.success(page);
        }
        Set<Long> userIds = page.getRecords().stream().map(SysRoleEntity::getUpdateUser).collect(Collectors.toSet());
        Map<Long, SysUserEntity> userMap = userService.getUserMap(new ArrayList<>(userIds));
        List<RoleVO> list = new LinkedList<>();
        page.getRecords().forEach(item -> {
            RoleVO roleVO = new RoleVO();
            BeanUtils.copyProperties(item, roleVO);
            roleVO.setUpdateBy(userMap.get(item.getUpdateUser()).getRealName());
            list.add(roleVO);
        });
        IPage<RoleVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resultPage.setRecords(list);
        return ResultUtil.success(resultPage);
    }

    /**
     * 自动生成角色编码
     *
     * @return
     */
    @GetMapping("/generate")
    public ResultUtil generateKey() {
        String newCode = sysRoleService.getMaxCode();
        return ResultUtil.success(newCode);
    }

    /**
     * 新增数据
     *
     * @param roleDTO 实体对象
     * @return 新增结果
     */
    @PostMapping("/save")
    public ResultUtil save(@RequestBody @Valid RoleDTO roleDTO) {
        if (Objects.isNull(roleDTO) || Objects.isNull(roleDTO.getSysRole())) {
            return ResultUtil.ERROR_ARG;
        }
        if (sysRoleService.saveInfo(roleDTO)) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        return ResultUtil.error(SysResultEnum.ADD_ROLE_FAIL);
    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/getById/{id}")
    public ResultUtil getById(@PathVariable("id") Long id) {
        if (NumberUtil.isNullOrLessEqual0(id)) {
            return ResultUtil.ERROR_ARG;
        }
        RoleVO roleVO = sysRoleService.getInfoById(id);
        return ResultUtil.success(roleVO);
    }

    /**
     * 更新角色信息
     *
     * @param roleDTO
     * @return
     */
    @PutMapping("/update")
    public ResultUtil update(@RequestBody @Valid RoleDTO roleDTO) {
        if (Objects.isNull(roleDTO) || Objects.isNull(roleDTO.getSysRole())
                || NumberUtil.isNullOrLessEqual0(roleDTO.getSysRole().getId())) {
            return ResultUtil.ERROR_ARG;
        }
        if (sysRoleService.updateInfo(roleDTO)) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        return ResultUtil.error(SysResultEnum.UPDATE_ROLE_FAIL);
    }

    /**
     * 启用角色
     *
     * @param id
     * @return
     */
    @PatchMapping("/enabled/{id}")
    public ResultUtil enabled(@PathVariable("id") Long id) {
        if (NumberUtil.isNullOrLessEqual0(id)) {
            log.error("##角色信息不存在");
            return ResultUtil.ERROR_ARG;
        }
        if (sysRoleService.updateStatus(id, EnabledEnum.ENABLE)) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        return ResultUtil.error(SysResultEnum.ROLE_ENABLED_USER_FAIL);
    }

    /**
     * 禁用角色
     *
     * @param id
     * @return
     */
    @PatchMapping("/disabled/{id}")
    public ResultUtil disabled(@PathVariable("id") Long id) {
        if (NumberUtil.isNullOrLessEqual0(id)) {
            log.error("##角色信息不存在");
            return ResultUtil.ERROR_ARG;
        }
        if (sysRoleService.updateStatus(id, EnabledEnum.DISABLE)) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        return ResultUtil.error(SysResultEnum.ROLE_DISABLED_USER_FAIL);
    }

    /**
     * 删除角色信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public ResultUtil delete(@PathVariable("ids") Long[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            return ResultUtil.ERROR_ARG;
        }
        if (sysRoleService.removeByIds(Arrays.asList(ids))) {
            // 删除角色与菜单直接的关系
            roleMenuService.delByRoleIds(Arrays.asList(ids));
            return ResultUtil.SUCCESS_NO_DATA;
        }
        log.error("##角色信息id={}删除失败", ids);
        return ResultUtil.error(SysResultEnum.DEL_ROLE_FAIL);
    }

    /**
     * 查询所有角色信息
     *
     * @return
     */
    @GetMapping("/list")
    public ResultUtil findList() {
        List<SysRoleEntity> resultList = sysRoleService.findList();
        return ResultUtil.success(resultList);
    }
}

